/**
 * Created by hengyu on 2019/1/17.
 */
/**
 * 实时交通
 * state: true启用，false关闭
 */
function shiShiJiaoTong(state) {
    if(state){
        var extent = [72.004, 0.8293, 137.8347, 55.8271];
        var baiduMercator = new ol.proj.Projection({
            code: 'baidu',
            extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
            units: 'm'
        });
        var bmercResolutions = new Array(19);
        for (var i = 0; i < 19; ++i) {
            bmercResolutions[i] = Math.pow(2, 18 - i);
        }
        ol.proj.addProjection(baiduMercator);
        ol.proj.addCoordinateTransforms('EPSG:4326', baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll);
        ol.proj.addCoordinateTransforms('EPSG:3857', baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc);
        var layer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                projection: 'baidu',
                tileUrlFunction: function(tileCoord) {
                    var x = tileCoord[1];
                    var y = -tileCoord[2]-1;
                    var z = tileCoord[0];
                    return "https://www.supermapol.com/iserver/services/traffic/rest/maps/baidu/zxyTileImage.png?&x={x}&y={y}&z={z}&width=256&height=256&transparent=true".replace('{x}', x).replace('{y}', y).replace('{z}', z);
                },
                tileGrid: (new ol.source.XYZ()).getTileGrid()
            })
        });
        layer.set("title","shiShiJiaoTong")
        mapApp.olMap.addLayer(layer);
    }else{
        removeLayer_HY(mapApp.olMap,"shiShiJiaoTong")
    }
}
/**
 * 规划选址
 * state: true启用，false关闭
 */
function guiHuaXuanzhi(state) {
    var Map=mapApp.olMap;
    if (state) {
        mapApp.olMap.un("singleclick", mapClickForPop)
        Map.removeLayer(getLayers_HY('xuanzhifenxi'));
        var source = new ol.source.Vector({wrapX: false});
        var xuanzhifenxiLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "#126889"
                })
            }),
            title: "xuanzhifenxi",
            zIndex: 99
        });
        Map.addLayer(xuanzhifenxiLayer);
        var xuanzhiinteraction = new ol.interaction.Draw({
            source: source,
            type: "Polygon"
        });
        xuanzhiinteraction.set("title","xuanzhifenxiPolygon")
        xuanzhiinteraction.on('drawstart', function (event) {
            xuanzhifenxiLayer.getSource().clear();
        });
        xuanzhiinteraction.on('drawend', function (event) {
            var tempinteraction=getInteraction(mapApp.olMap,"xuanzhifenxiPolygon")
            if(tempinteraction){
                mapApp.olMap.removeInteraction(tempinteraction)
            }
            var drawendFeature = event.feature;
            var format = new ol.format.WKT();
            var xuanzhipolygonWKT = format.writeFeature(drawendFeature);
            //xzfxgetData(xuanzhipolygonWKT)

            var frameName = window.top.getghxzFrames();
            window.top.frames[frameName].ghxzFun(xuanzhipolygonWKT)
        });
        Map.addInteraction(xuanzhiinteraction);
    } else {
        closeghxzFun();

        mapApp.olMap.on("singleclick", mapClickForPop)
        Map.removeLayer(getLayers_HY('xuanzhifenxi'));
        Map.removeLayer(getLayers_HY('xuanzhifenxiResult'));
        Map.removeLayer(getLayers_HY('wktLayer'));
        Map.removeInteraction(getInteraction(mapApp.olMap,"xuanzhifenxiPolygon"));
    }
}
/**
 * 根据title获取地图交互
 */
function getInteraction(map1, interactionTitle) {
    var interactions = map1.getInteractions().getArray();
    for(var i = 0; i < interactions.length; i++) {
        if(interactions[i].getProperties().title == interactionTitle) {
            return interactions[i]
        }
    }
}
/**
 * 移除图层
 */
function removeLayer_HY(map1, layerName) {
    var layers = map1.getLayers().getArray();
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].getProperties().title == layerName) {
            map1.removeLayer(layers[i]);
            i--
        }
    }
}
/**
 * 地图单击弹窗事件
 */
function mapClickForPop(evt) {
    var tempMap = mapApp.olMap
    var tempOverlays = tempMap.getOverlays().getArray();
    var pop
    for (var i = 0; i < tempOverlays.length; i++) {
        if (tempOverlays[i].get("title") == "popOverlay") {
            pop = tempOverlays[i];
            pop.hide()
        }
    }
    if (pop) {
        var templayers = []
        tempMap.forEachLayerAtPixel(evt.pixel, function (layer) {
            templayers.push(layer)
        })
        var templayer=getLayers_HY(templayers[0].get("title"))
        if(!templayer){
            return
        }
        var source = templayer.getSource()
        var popcoord = evt.coordinate;
        pop.set("location",popcoord)
        var view = tempMap.getView();
        var viewResolution = view.getResolution();
        if (source instanceof ol.source.WMTS) {
            var pickurl=source.getUrls()[0].replace(/mapserver.*/g,"mapserver/pickup/"+templayers[0].get("serviceLayerName")+"/getData?")
            //var url='http://sdi.zjzwfw.gov.cn/mapserver/pickup/'+serveName+'/getData?x='+lon+'&y='+lat+'&l='+mapLevel+'&pixelX='+pixelX+'&pixelY='+pixelY+'&styleId={styleId}&ratio=1&control={ cmdAll:false, layers:[{ id:"面状水系", filters:{Q_fcode_S_EQ:2101010500}, idFilter:"818009",display:false }], order:[]}'
            //var url1="http://sdi.zjzwfw.gov.cn/mapserver/pickup/zjvmap/getData?x=109280&y=21748&l=17&pixelX=68.98832129966468&pixelY=155.61451732367277&styleId=tdt_biaozhunyangshi_2017"
            var popcoord = evt.coordinate;
            var view = tempMap.getView();
            var viewResolution = view.getResolution();
            var column=Math.floor(parseFloat(popcoord[0]-(-180))/(256*viewResolution))
            var row=Math.floor(parseFloat(90-popcoord[1])/(256*viewResolution))
            var level=view.getZoom()
            var pixelX=(popcoord[0]-(column*256*viewResolution-180))/viewResolution
            var pixelY=((90-(row)*256*viewResolution)-popcoord[1])/viewResolution
            pickurl=pickurl+"x="+column+"&y="+row+"&l="+(level)+"&pixelX="+pixelX+"&pixelY="+pixelY+"&styleId="+templayers[0].get("styleID")+"&tilesize=256"
            $.ajax({
                type: "GET",
                url: pickurl,
                success: function (obj) {
                    PopContent(pop,templayers[0],obj)
                }
            })
        }else if(source instanceof ol.source.Vector){
            var features=tempMap.getFeaturesAtPixel(evt.pixel,{layerFilter:function(filterlayer){
                if(filterlayer.getProperties().title==templayers[0].get("title")){
                    return true
                }
            }})
            if(features.length>0){
                PopContent(pop,templayers[0],features[0].getProperties())
            }
        }else if (source instanceof ol.source.TileWMS) {
            var url = source.getGetFeatureInfoUrl(
                evt.coordinate, tempMap.getView().getResolution(), tempMap.getView().getProjection(), {
                    'INFO_FORMAT': 'application/json'
                });
            // var url = source.getGetFeatureInfoUrl(
            //     evt.coordinate,tempMap.getView().getResolution(), tempMap.getView().getProjection(), {
            //         'INFO_FORMAT': 'application/json'
            //     });
            if (url) {
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (obj) {
                        if (obj.features.length > 0) {
                            var popupcoordinate = popcoord
                            var properties = obj.features[0].properties
                            PopContent(pop,templayers[0],properties)
                            //map.getView().animate({center:feature.getGeometry().getCoordinates()});
                        }
                    }
                })
            }
        }
    }
}
/**
 * 根据图层title获取图层
 */
function getLayers_HY(layersName) {
    var mapLayers = mapApp.olMap.getLayers().getArray()
    if (layersName instanceof Array) {
        var resultLayers = [];
        for (var j = 0; j < layersName; j++) {
            for (var i = 0; i < mapLayers.length; i++) {
                if (mapLayers[i].getProperties().title == layerName[j]) {
                    resultLayers.push(mapLayers[i]);
                }
            }
        }
        return resultLayers;
    } else {
        if (layersName) {
            for (var i = 0; i < mapLayers.length; i++) {
                if (mapLayers[i].getProperties().title == layersName) {
                    return mapLayers[i];
                }
            }
        }
    }
}
/**
 * 获取选址分析结果
 *  * data:后台选址分析返回的结果对象
 */
function getXZFXresult(data) {
    if (data) {
        var xuanzhifenxiResult=getLayers_HY("xuanzhifenxiResult")
        var ctinteraction=getInteraction(mapApp.olMap,"xuanzhifenxiPolygon")
        if(ctinteraction){
            mapApp.olMap.removeInteraction(ctinteraction)
        }
        var xuanzhifenxiResult=getLayers_HY("xuanzhifenxiResult")
        if(!xuanzhifenxiResult){
            xuanzhifenxiResult=new ol.layer.Vector({
                source:new ol.source.Vector(),
                style:function (feature) {
                    var strokeWidth=3
                    var strokeColor="orange"
                    var fillColor="rgba(255,255,255,0.5)"
                    if(feature.get("selected")=="true"){
                        strokeWidth=4;
                        //strokeColor="blue";
                        fillColor="rgba(100,149,237,0.5)"
                    }
                    return  new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: fillColor
                        }),
                        stroke: new ol.style.Stroke({
                            color: strokeColor,
                            width:strokeWidth
                        })
                    })
                } ,
                title: "xuanzhifenxiResult",
                zIndex:1000
            })
            mapApp.olMap.addLayer(xuanzhifenxiResult);
        }
        xuanzhifenxiResult.getSource().clear();
        var format = new ol.format.WKT();
        var polygons=data.result.siteList
        for(var i=0;i<polygons.length;i++){
            var resultFeature = format.readFeature(polygons[i].zggeom);
            resultFeature.set("id",polygons[i].smId)
            var resultSource=xuanzhifenxiResult.getSource();
            resultSource.addFeature(resultFeature)
        }
    }
}
/**
 * 读取wkt至地图
 */
function addWKT2map(wkt){

        var tempLayer=getLayers_HY("tempWKTLayer")
        if(tempLayer){
            mapApp.olMap.removeLayer(tempLayer)
        }
        var format = new ol.format.WKT();
        wkt=/(Polygon|POLYGON|MULTIPOLYGON|Multipolygon).*/g.exec(wkt)[0]
        var wktFeature = format.readFeature(wkt);
        var tempLayer = new ol.layer.Vector({
            source: new ol.source.Vector(),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "#126889"
                })
            }),
            title: "wktLayer",
            zIndex:1000
        })
        mapApp.olMap.addLayer(tempLayer)
        if(wktFeature){
            tempLayer.getSource().addFeature(wktFeature)
            mapApp.olMap.getView().fit(wktFeature.getGeometry())
        }
}
/**
 * 地图显示选址分析多边形
 *id:多边形id
 * state：打开关闭状态
 */
function zoomToPolygon(id,state) {

    var ctfxResultLayer=getLayers_HY("chongtufenxiResult")
    var xzfxResultLayer=getLayers_HY("xuanzhifenxiResult")
    if(state){
        if(ctfxResultLayer){
            var features=ctfxResultLayer.getSource().getFeatures();
            for(var i=0;i<features.length;i++){
                if(features[i].get("id")==id){
                    features[i].set("selected","true")
                    mapApp.olMap.getView().fit(features[i].getGeometry())
                    mapApp.olMap.getView().setZoom(mapApp.olMap.getView().getZoom())
                }else{
                    features[i].set("selected","false")
                }
            }
        }else if(xzfxResultLayer){
            var features=xzfxResultLayer.getSource().getFeatures();
            for(var i=0;i<features.length;i++){
                if(features[i].get("id")==id){
                    features[i].set("selected","true")
                    mapApp.olMap.getView().fit(features[i].getGeometry())
                    mapApp.olMap.getView().setZoom(mapApp.olMap.getView().getZoom())
                }else{
                    features[i].set("selected","false")
                }
            }
        }
    }else{
        if(ctfxResultLayer){
            var features=ctfxResultLayer.getSource().getFeatures();
            for(var i=0;i<features.length;i++){
                features[i].set("selected","false")
            }
        }else if(xzfxResultLayer){
            var features=xzfxResultLayer.getSource().getFeatures();
            for(var i=0;i<features.length;i++){
                features[i].set("selected","false")
            }
        }
    }
}
/**
 * 根据传入的多边形返回其中心点经纬度
 * id:多边形smid
 * return: 120.2525,30.1545
 */
function polygonCenter(id) {
    var xzfxResultLayer=getLayers_HY("xuanzhifenxiResult")
    if(xzfxResultLayer){
        var features=xzfxResultLayer.getSource().getFeatures();
        for(var i=0;i<features.length;i++){
            if(features[i].get("id")==id){
                var extent=features[i].getGeometry().getExtent()
                var center=((extent[0]+extent[2])/2)+","+((extent[1]+extent[3])/2)
                return center
            }
        }
    }
}
